package com.song.files.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.song.files.resource.FileResource;
import com.song.files.service.UploaderService;
import com.song.utils.extend.CloudServiceResource;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class UploaderServiceImpl implements UploaderService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private CloudServiceResource cloudServiceResource;

    @Autowired
    private FileResource fileResource;

    @Autowired
    private Sid sid;

    @Override
    public String uploadFdfs(MultipartFile file, String fileExtName) throws Exception {

        // 存储图片并返回图片路径
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                fileExtName,
                null);
        return storePath.getFullPath();
    }

    /**
     * 在阿里OSS中上传文件
     * @param file
     * @param userId
     * @param fileExtName
     */
    @Override
    public String uploadOSS(MultipartFile file, String userId, String fileExtName) throws Exception {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = fileResource.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = cloudServiceResource.getAccessKeyId();
        String accessKeySecret = cloudServiceResource.getAccessKeySecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = fileResource.getBucketName();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String fileName = sid.nextShort();
        // objectName == image/face/userId/songsong.png
        String objectName = fileResource.getObjectName()
                + "/" + userId + "/" + fileName + "." + fileExtName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = file.getInputStream();
        // 创建PutObject请求。
        ossClient.putObject(bucketName, objectName, inputStream);

        // 关闭OSSClient
        ossClient.shutdown();
        return objectName;
    }
}
